package com.xm2.demo.system.order.service;

import com.xm2.demo.model.Form;
import com.xm2.demo.model.State;
import com.xm2.demo.model.StateRecord;
import com.xm2.demo.system.order.dao.OrderRepository;
import com.xm2.demo.system.order.dao.StateRecordRepository;
import com.xm2.demo.system.order.dao.StateRepository;
import com.xm2.demo.system.order.ov.OrderOv;
import com.xm2.demo.system.order.ov.OrderPage;
import com.xm2.demo.utils.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author
 * @Date 2018/12/12 19:59
 * @Description
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private StateRepository stateRepository;
    @Autowired
    private StateRecordRepository stateRecordRepository;

    // 普通分页查询
    @Override
    public Pagination findByOrderPagination(Pagination pagination) {
        pagination.setTotalRows(orderRepository.findAll().size());
        Pageable pageable = new PageRequest(pagination.getCurrentPage(), pagination.getSize(), Sort.Direction.ASC, "id");
        pagination.setList(orderRepository.findAll(pageable).getContent());
        List<OrderOv> orderOvs = new ArrayList<>();
        for (Form form : (List<Form>) pagination.getList()) {
            OrderOv orderOv = new OrderOv();
            orderOv.setForm(form);
            orderOv.setStatus(stateRepository.findById(form.getStateId()).getState());
            orderOvs.add(orderOv);
        }
        pagination.setList(orderOvs);
        return pagination;
    }

    //根据时间分页查询
    @Override
    public Pagination
    findByDatePagination(OrderPage orderPage) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        orderPage.setTotalRows(orderRepository.findByDatePagination(dateFormat.parse(orderPage.getStartDate()), dateFormat.parse(orderPage.getStopDate())).size());
        orderPage.setList(orderRepository.findByDatePaginationLimit(dateFormat.parse(orderPage.getStartDate()), dateFormat.parse(orderPage.getStopDate()), orderPage.getStartRow(), orderPage.getSize()));
        List<OrderOv> orderOvs = new ArrayList<>();
        for (Form form : (List<Form>) orderPage.getList()) {
            OrderOv orderOv = new OrderOv();
            orderOv.setForm(form);
            orderOv.setStatus(stateRepository.findById(form.getStateId()).getState());
            orderOvs.add(orderOv);
        }
        orderPage.setList(orderOvs);
        return orderPage;
    }

    //根据订单号查询不分页
    @Override
    public Pagination findByOrderId(OrderPage orderPage) {
        orderPage.setTotalPage(1);
        orderPage.setSize(20);
        orderPage.setList(stateRecordRepository.findByOrderId(orderPage.getOrderId()));
        List<OrderOv> orderOvs = new ArrayList<>();
        for (StateRecord stateRecord : (List<StateRecord>) orderPage.getList()) {
            OrderOv orderOv = new OrderOv();
            Form form = new Form();
            form.setStateId(stateRecord.getStateId());
            form.setOrderId(stateRecord.getOrderId());
            form.setMoney(stateRecord.getMoney());
            form.setFormDate(stateRecord.getFormDate());
            form.setCustomerName(stateRecord.getCustomerName());
            form.setSalesmanName(stateRecord.getSalesmanName());
            orderOv.setForm(form);
            orderOv.setStatus(stateRepository.findById(form.getStateId()).getState());
            orderOvs.add(orderOv);
        }
        orderPage.setList(orderOvs);
        return orderPage;
    }

    // 生成新的订单
    @Override
    @Transactional
    public void addOrder(StateRecord stateRecord) {
        //根据当前时间生成订单号
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        stateRecord.setOrderId(dateFormat.format(date));
        Form form = new Form();
        form.setStateId(stateRecord.getStateId());
        form.setOrderId(stateRecord.getOrderId());
        form.setMoney(stateRecord.getMoney());
        form.setFormDate(new Date());
        form.setCustomerName(stateRecord.getCustomerName());
        orderRepository.save(form);
        stateRecordRepository.save(stateRecord);
    }

    // 修改订单状态
    @Override
    @Transactional
    public void updateOrder(StateRecord stateRecord, String name, String phone) throws Exception {
        Form form = orderRepository.findByOrderId(stateRecord.getOrderId());
        if (form.getStateId() + 1 == stateRecord.getStateId()) {
            stateRecord.setSalesmanName(name);
            stateRecord.setOrderId(form.getOrderId());
            stateRecord.setMoney(form.getMoney());
            stateRecord.setFormDate(new Date());
            stateRecord.setPhone(form.getPhone());
            stateRecord.setCustomerName(form.getCustomerName());
            if (form.getStateId() == 2 || form.getStateId() == 3 ||
                    form.getStateId() == 4 || form.getStateId() == 7 || form.getStateId() == 8) {
                orderRepository.updateOrderStateAndName(stateRecord.getStateId(), stateRecord.getOrderId(), name, phone);
            } else {
                orderRepository.updateOrderStateAndName(stateRecord.getStateId(), stateRecord.getOrderId(), "未绑定", "未绑定");
            }

            stateRecordRepository.save(stateRecord);
        } else {
            throw new Exception("状态修改失败");
        }
    }

    @Override
    public void deleteOrder(Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            orderRepository.delete(ids[i]);
        }
    }

    @Override
    public List<State> findStatus(String stateArr) {
        String[] stateId = stateArr.split(",");
        Integer[] stateIdArr = new Integer[stateId.length];
        List<State> states = new ArrayList<>();
        for (int i = 0; i < stateId.length; i++) {
            stateIdArr[i] = Integer.parseInt(stateId[i]);
            states.add(stateRepository.findById(stateIdArr[i]));
        }
        return states;
    }

    @Override
    public Pagination findByUsername(String username, Pagination pagination) {
        pagination.setTotalRows(orderRepository.findByUsername(username).size());
        Pageable pageable = new PageRequest(pagination.getCurrentPage(), pagination.getSize(), Sort.Direction.ASC, "id");
        pagination.setList(orderRepository.findByUsername(username, pageable));
        List<OrderOv> orderOvs = new ArrayList<>();
        for (Form form : (List<Form>) pagination.getList()) {
            OrderOv orderOv = new OrderOv();
            orderOv.setForm(form);
            orderOv.setStatus(stateRepository.findById(form.getStateId()).getState());
            orderOvs.add(orderOv);
        }
        pagination.setList(orderOvs);
        return pagination;
    }

}
